package com.zg.datapush.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zg.common.core.R;
import com.zg.common.core.dao.datapush.dao.DpFieldMappingDao;
import com.zg.common.core.dao.datapush.entity.DpFieldMapping;
import com.zg.datapush.vo.DpFieldMappingVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 字段映射服务
 * @author zg
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class DpFieldMappingService {

    private final DpFieldMappingDao fieldMappingDao;

    /**
     * 根据任务ID查询字段映射
     */
    public List<DpFieldMappingVo> listByTaskId(Long taskId) {
        List<DpFieldMapping> entities = fieldMappingDao.list(
            new LambdaQueryWrapper<DpFieldMapping>()
                .eq(DpFieldMapping::getTaskId, taskId)
                .orderByAsc(DpFieldMapping::getSortOrder)
        );

        return entities.stream()
            .map(entity -> {
                DpFieldMappingVo vo = new DpFieldMappingVo();
                BeanUtil.copyProperties(entity, vo);
                return vo;
            })
            .collect(Collectors.toList());
    }

    /**
     * 新增字段映射
     */
    public R<DpFieldMapping> add(DpFieldMappingVo vo) {
        DpFieldMapping entity = new DpFieldMapping();
        BeanUtil.copyProperties(vo, entity);

        fieldMappingDao.save(entity);
        return R.success(entity);
    }

    /**
     * 更新字段映射
     */
    public R<DpFieldMapping> update(DpFieldMappingVo vo) {
        DpFieldMapping entity = fieldMappingDao.getById(vo.getId());
        if (entity == null) {
            return R.error("字段映射不存在");
        }

        BeanUtil.copyProperties(vo, entity);
        fieldMappingDao.updateById(entity);
        return R.success(entity);
    }

    /**
     * 删除字段映射
     */
    public R<Void> delete(List<Long> ids) {
        fieldMappingDao.removeBatchByIds(ids);
        return R.success();
    }

    /**
     * 批量保存字段映射
     */
    @Transactional
    public R<Void> batchSave(Long taskId, List<DpFieldMappingVo> mappings) {
        // 先删除原有的映射
        fieldMappingDao.remove(
            new LambdaQueryWrapper<DpFieldMapping>()
                .eq(DpFieldMapping::getTaskId, taskId)
        );

        // 保存新的映射
        for (int i = 0; i < mappings.size(); i++) {
            DpFieldMappingVo vo = mappings.get(i);
            DpFieldMapping entity = new DpFieldMapping();
            BeanUtil.copyProperties(vo, entity);
            entity.setTaskId(taskId);
            entity.setSortOrder(i + 1);
            fieldMappingDao.save(entity);
        }

        return R.success();
    }
}
